<!-- 开票申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="propose" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
				<u-form-item label="申请时间" required>
				  <u--input v-model="model.createTime" disabled></u--input>
				</u-form-item>
        <u-form-item label="销售方单位" prop="sellerUnit" required>
          <h-select-company-input
            style="width: 100%"
            v-model="model.sellerUnit"
            border="surround"
            placeholder="请选择销售方单位"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.sellerUnit"
						@input="sellerUnitBack"
          ></h-select-company-input>
        </u-form-item>
        <u-form-item label="经营团队" prop="teamId" required>
          <h-select-team-input-popup
            style="width: 100%"
            v-model="model.teamId"
            objectField="model.teamId"
            placeholder="请选择经营团队"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            :tdlx="3"
            border="surround"
						@realChange="teamIdBack"
          ></h-select-team-input-popup>
        </u-form-item>
        <u-form-item label="开票人" prop="invoiceApplicant" required>
          <h-select-person-input-popup
						disabled
            v-model="model.invoiceApplicant"
            class="w-100"
            placeholder="请选择开票人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="开票类型" prop="invoiceCategory" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.invoiceCategory"
            objectField="model.invoiceCategory"
            placeholder="请选择开票类型"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="invoice_type"
						@change="changeInvoiceCategory"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="是否作废" prop="isCrossMonthInvalid">
          <h-select-input-tag
            class="w-100"
            v-model="model.isCrossMonthInvalid"
            objectField="model.isCrossMonthInvalid"
            placeholder="请选择是否作废"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            border="surround"
            dictName="YES_OR_NO"
						@change="radioChange"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="总开票金额（元）" prop="invoiceTotalAmount" required>
					<h-money-input disabled placeholder="请输入总开票金额，允许输入负数" v-model="model.invoiceTotalAmount" :isMinus="false"></h-money-input>
        </u-form-item>
				<view v-if="model.isCrossMonthInvalid!=0">
					<u-form-item label="关联已开票申请单" prop="relBillId" required>
					  <h-select-finance-invoice-bill-input-popup
					    :sellerUnit="model.sellerUnit"
					    :teamId="model.teamId"
					    v-model="model.relBillId"
					    placeholder="请选择关联已开票申请单"
							:disabled="!model.sellerUnit || !model.teamId"
					    searchPlaceholder="请输入单据编号"
					    border="surround"
					    style="width: 100%"
					    suffixIcon="arrow-down-fill"
							repeat
					    :suffixIconStyle="{ color: '#B2B2B2' }"
					    @change="relBillIdChange"
					  ></h-select-finance-invoice-bill-input-popup>
					</u-form-item>
				</view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">发票信息</view>
				<view style="color: #f56c6c;">作废时开票金额请填负数！</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="addForm">新增</u-button>
        </view>
				<view>
					<InvoiceFormInfo v-for="(item, index) in formData" :key="index" :isCancel="model.isCrossMonthInvalid" :item="item" :index="index" @edit="handleEditForm" @remove="handleRemoveForm" @copy="handleCopyForm"/>
				</view>
        <u-popup mode="bottom" :show="showFormModal" @close="closeFormModal">
          <InvoiceForm
            ref="dataForm"
            :index="index"
            :teamId="model.teamId"
            :sellerUnit="model.sellerUnit"
            @submit="handleFormSubmit"
            @close="closeFormModal"
						:isCancel="model.isCrossMonthInvalid"
          />
        </u-popup>
      </view>
			<view class="basic-style">
			  <view class="basic-title basic-border">税率信息</view>
			  <view v-for="(item, index) in taxRateData" :key="index">
			  	<RateFormInfo
						:isCancel="model.isCrossMonthInvalid"
			  		:item="item"
			  		:index="index"
			  		@edit="handleEditFormRate"
			  		@remove="handleRemoveFormRate"
			  		@copy="handleCopyFormRate"
			  		:disabled="false"
			  	/>
			  </view>
			  <u-popup mode="bottom" :show="showFormModalRate" :closeOnClickOverlay="false">
			    <RateForm
						ref="dataFormRate"
						:isCancel="model.isCrossMonthInvalid"
						:index="index"
						@submit="handleFormSubmitRate"
						@close="closeFormModalRate" />
			  </u-popup>
			</view>

      <view class="basic-style">
        <u-form-item label="业主单位" prop="buyerUnit" required>
          <!-- <h-select-customer-input-popup
            style="width: 100%"
            v-model="model.buyerUnit"
            objectField="model.buyerUnit"
            commercialType="1"
            placeholder="请选择业主单位"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            border="surround"
          ></h-select-customer-input-popup> -->
					<h-select-input-tag
					  class="w-100"
						:disabled="formData.length == 0"
					  v-model="model.buyerUnit"
					  objectField="model.buyerUnit"
					  placeholder="请选择业主单位"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
					  border="surround"
					  :dictName="buyerUnit"
						@change="selectBuyerUnit"
					></h-select-input-tag>
        </u-form-item>
        <u-form-item  prop="taxpayerIdNo" required>
					<span slot="label" style="position: relative;">
						<span style="color: #f56c6c;line-height: 20px;font-size: 20px;position: absolute;top: 3px;left: -9px;">*</span>
						<span style="font-size: 14px; line-height: 20px;color: rgb(178, 178, 178);">纳税人识别号</span>
						<span style="color: #f56c6c; font-size: 12px; line-height: 20px;">(如果没有税号请填写无)</span>
					</span>
          <u--input v-model="model.taxpayerIdNo" placeholder="请输入纳税人识别号"></u--input>
        </u-form-item>
        <u-form-item label="单位地址" prop="companyAddress" required>
          <u--input v-model="model.companyAddress" placeholder="请输入单位地址"></u--input>
        </u-form-item>
        <u-form-item label="单位电话" prop="companyTel">
          <u--input v-model="model.companyTel" placeholder="请输入单位电话"></u--input>
        </u-form-item>
        <u-form-item label="开户行" prop="bankName" required>
          <u--input v-model="model.bankName" placeholder="请输入开户行"></u--input>
        </u-form-item>
        <u-form-item label="银行账号" prop="bankAccountNo" required>
          <u--input v-model="model.bankAccountNo" placeholder="请输入银行账号"></u--input>
        </u-form-item>
        <u-form-item label="发票备注" prop="invoiceRemark" required>
          <u--textarea confirm-type="send" v-model="model.invoiceRemark" placeholder="请输入发票备注"></u--textarea>
        </u-form-item>
        <u-form-item label="附言" prop="postscript">
          <u--input v-model="model.postscript" placeholder="请输入附言"></u--input>
        </u-form-item>
      </view>
			
			<view class="basic-style">
			  <view class="basic-title basic-border">开票信息</view>
			  <!-- <view class="space-y-1 py-1">
			    <u-button size="small" type="primary" @click="addForm">新增</u-button>
			  </view> -->
				 <view v-for="(item, index) in dataSource" :key="index">
					 <formInfoRecord :item="item" :index="index" />
				 </view>
			</view>
			
      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachments" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachments" v-model="model.attachments" :isDelete="true"></file-list>
        </view>
      </view>

			<view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
				<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, info,edit,queryEmpIdByCompanyIdAndPostCode,queryInvoiceExpensesDetailByBillId, erpFinanceInvoiceTaxRateRecordList, queryContractRateFinal, queryContractPaymentNodeFinal } from '@/api/finance/ErpFinanceInvoiceBillForm'
import { addInvoiceHandleRecordList, erpOmcProjectId, querySupplierByIds,queryByIdInvoiceChildren,erpFinanceInvoiceHandleRecordList,erpOmcContractManagerEntrustFinalList } from '@/api/index'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import fileList from '@/pages/synergy/components/fileList.vue'
import InvoiceForm from './components/InvoiceForm.vue'
import InvoiceFormInfo from './components/InvoiceFormInfo.vue'
import RateForm from './components/RateForm.vue' // 税率表单
import RateFormInfo from './components/RateFormInfo.vue' // 税率列表
import formInfoRecord from './components/InvoiceApplication.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
export default {
  name: 'ErpFinanceInvoiceApplicationBillForm',
  components: { fileList, InvoiceForm, InvoiceFormInfo,ProcessNodeConfiguration,formInfoRecord, RateForm, RateFormInfo },
  data() {
    return {
			buyerUnit: '',
      backUpApplicant: '',
      backUpTeamId: '',
      isReset: false,
      resetKey: '',
      index: null,
      showFormModal: false,
			showFormModalRate: false, // 税率表单显隐
      id: '',
      basicForm: {},
			basicFormRate: {}, // 税率表单
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        billNo: '',
        proposer: '',
        proposerDeptId: '',
        createTime: '',
        // 基本信息 - 非公用
        checkStatus: '0',
        invoiceCategory: '1',
        isCrossMonthInvalid: '1',
        invoiceTotalAmount: '',
        relBillId: '',
        buyerUnit: '',
				invoiceExpensesDetails: [],
        taxpayerIdNo: '',
        companyAddress: '',
        companyTel: '',
        bankName: '',
        bankAccountNo: '',
        invoiceRemark: '',
        postscript: '',
				sellerUnit: '',
      },
      formData: [],
			taxRateData: [], // 税率信息
      rules: {
        invoiceCategory: [{ required: true, message: '请输入开票类型!', trigger: ['blur', 'change'] }],
        invoiceApplicant: [{ required: true, message: '请选择开票人!', trigger: ['blur', 'change'] }],
        invoiceTotalAmount: [{ required: true, message: '请输入总开票金额!', trigger: 'blur' }],
        sellerUnit: [{ required: true, message: '请选择销售方单位!', trigger: ['blur', 'change'] }],
        teamId: [{ required: true, message: '请选择经营团队!', trigger: ['blur', 'change'] }],
        relBillId: [{ required: true, message: '请选择关联已开票申请单!', trigger: ['blur', 'change'] }],
        buyerUnit: [{ required: true, message: '请输入业主单位!', trigger: ['blur', 'change'] }],
        taxpayerIdNo: [{ required: true, message: '请输入纳税人识别号!', trigger: ['blur', 'change'] }],
        companyAddress: [{ required: true, message: '请输入单位地址!', trigger: ['blur', 'change'] }],
        bankName: [{ required: true, message: '请输入开户行!', trigger: ['blur', 'change'] }],
        bankAccountNo: [
          { required: true, message: '请输入银行账号!', trigger: ['blur', 'change'] }
        ],
        invoiceRemark: [{ required: true, message: '请输入发票备注!', trigger: ['blur', 'change'] }],
				companyTel: [
					{ pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}|(0\d{2,3})-?(\d{7,8})$/, message: '请输入正确的手机号!' },
				],
      },
			isSubmit: false,
			teamIdBackups: null,
			sellerUnitBackups: null,
			relBillIdBackups: null,
			dataSource: [],
			dictOptions: {},
			//代码生成后需手动设置流程编码
			flowCode: 'onl_erp_finance_invoice_application_bill',
			formUrl: "/erp/finance/invoice/modules/ErpFinanceInvoiceApplicationBillForm",
			formUrlMobile: "/pages/synergy/invoiceApplicationBill",
			processId: '1528558426076033025',
			beanName: 'erpFinanceInvoiceApplicationBillServiceImpl',
			editCount: 0,
			oldprojectContract: null
    }
  },
  onLoad({ id }) {
    this.id = id || ''
		if (this.id) {
		  this.initInfo()
		} else {
		  this.initForm()
		  this.initBillNo()
			this.oldprojectContract = null
		}
		this.initDicts()
  },
  computed: {
    ...mapState(['userInfo']),
    formTotal() {
      return this.formData.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
    },
  },
  methods: {
		relBillIdChange(item) {
			let Id;
			if(typeof item == 'string'){
				Id = item
			} else {
				Id = item.id
			}
			// this.relBillIdBackups = item.id
			this.relBillIdBackups = Id
			if(Id){
				queryInvoiceExpensesDetailByBillId({billId:Id}).then(res=>{
					if(!!res&&!!res.result&&res.result.length!=0){
						let dataSource=this.handleinvoiceData(res.result);
						dataSource=this.handleOnInvoiceAmount(dataSource);
						// 调用原有带出数据方法
						this.formData = dataSource;
						this.expensesDetail(dataSource);
						this.initBuyerInfo(dataSource[0]);
						// 业主单位
						this.$set(this.model,'buyerUnit',null)
						// 纳税人识别号 taxpayerIdNo
						this.$set(this.model,'taxpayerIdNo',null)
						// 单位地址
						this.$set(this.model,'companyAddress',null)
						// 开户行
						this.$set(this.model,'bankName',null)
						// 银行账号
						this.$set(this.model,'bankAccountNo',null)
					}
				}).catch(e=>{
					console.error('异常')
				})
			}
		},
		//开票金额取负数
		handleinvoiceData(dataSource){
			dataSource.forEach(item=>{
			 item.invoiceAmount=(0-item.invoiceAmount)
			});
			return dataSource;
		},
		//调整最新的已开票金额
		handleOnInvoiceAmount(dataSource){
			dataSource.forEach(item=>{
				queryContractPaymentNodeFinal({id:item.contractFund}).then(res=>{
					if(res.result){
						let data=res.result.records
						if(data){
							item.onInvoiceAmount=data[0].invoicePaidAmount
						}
					}
				})
			});
			return dataSource;
		},
		expensesDetail(data) {
			if(this.editCount<2){// 为了控制刚进页面时第一次加载不自动带出业主数据
				this.editCount++;
			}
			this.formData = data
			let count = 0
			this.formData.forEach((item, index) => {
				count = count + item.invoiceAmount
			})
			this.$set(this.model,'invoiceTotalAmount',Number(count).toFixed(2))
			if(data.length>0){
				//处理业主单位
				this.handleBuyerUnit(data[0].projectContract);
			}else{
				this.taxRateData = []
			}
		},
		// 开票类型为普票时，开户行和银行账号为非必填，开票类型为专票时必填
		changeInvoiceCategory(){
			if(!!this.model.invoiceCategory&&this.model.invoiceCategory!='1'){
				this.$delete(this.rules,'bankName')
				this.$delete(this.rules,'bankAccountNo')
			}else{
				this.$set(this.rules,'bankName',[ { required: true, message: '请输入开户行!', trigger: 'blur'} ])
				this.$set(this.rules,'bankAccountNo',[
					{ required: true, message: '请输入银行账号!', trigger: 'blur'},
				])
			}
		},
		teamIdBack(val) {
			let item = [val]
			//判断不为空
			if(!!this.model.teamId && item.length > 0|| this.model.relBillId) {
				//判断团队是否变化
				if(this.teamIdBackups !== item[0].id||this.relBillIdBackups !== this.model.relBillId) {
					if(this.formData.length > 0||!!this.model.relBillId) {
						const that = this;
						uni.showModal({
							title: "是否确认",
							content: "是否确认切换经营团队，此操作将会清空关联已开票申请单和开票信息明细中已填写的所有信息？",
							success(res) {
							  if (res.confirm) {
							    //确认后进行改变
							    that.teamIdBackups = that.model.teamId
							    that.relBillIdBackups = null
									that.formData = [] // 清空子表数据
							    // 清空关联已开票申请单
							    that.$set(that.model, 'relBillId', '')
									that.taxRateData = []; // 税率信息
							    //清空子表数据
							    that.dataSource = []
							    // 清空由表带出的数据
							    // 业主单位
							    that.$set(that.model,'buyerUnit','')
							    // 纳税人识别号 taxpayerIdNo
							    that.$set(that.model,'taxpayerIdNo','')
							    // 单位地址
							    that.$set(that.model,'companyAddress','')
							    // 开户行
							    that.$set(that.model,'bankName','')
							    // 银行账号
							    that.$set(that.model,'bankAccountNo','')
							    
							    // 总开票金额
									that.$set(that.model,'invoiceTotalAmount',0)
							    // if (that.model.isCrossMonthInvalid == '0'){
							    // 	that.$set(that.model,'invoiceTotalAmount',0)
							    // }
							  } else if (res.cancel) {
									that.model.teamId = that.teamIdBackups
									that.model.relBillId = that.relBillIdBackups
							  }
							},
							// success() {
							// 	//确认后进行改变
							// 	that.teamIdBackups = that.model.teamId
							// 	that.relBillIdBackups = null
							// 	// 清空关联已开票申请单
							// 	that.$set(that.model, 'relBillId', '')
							// 	//清空子表数据
							// 	that.dataSource = []
							// 	// 清空由表带出的数据
							// 	// 业主单位
							// 	that.$set(that.model,'buyerUnit','')
							// 	// 纳税人识别号 taxpayerIdNo
							// 	that.$set(that.model,'taxpayerIdNo','')
							// 	// 单位地址
							// 	that.$set(that.model,'companyAddress','')
							// 	// 开户行
							// 	that.$set(that.model,'bankName','')
							// 	// 银行账号
							// 	that.$set(that.model,'bankAccountNo','')

							// 	// 总开票金额
							// 	if (that.model.isCrossMonthInvalid == '0'){
							// 		that.$set(that.model,'invoiceTotalAmount',0)
							// 	}
							// },
							// onCancel() {
							// 	that.model.teamId = that.teamIdBackups
							// 	that.model.relBillId = that.relBillIdBackups
							// }
						});
					} else {
						this.teamIdBackups = item[0].id
					}
				}
			}
		},
		radioChange(item){
			if (item == 0) {
				this.formData = []
				this.taxRateData = []; // 税率信息
				let count = 0
				this.formData.forEach((item, index) => {
					count = count + Number(item.invoiceAmount)
				})
				this.model.invoiceTotalAmount = Number(count).toFixed(2)
				this.model.relBillId = ''
				this.$refs.form.clearValidate('invoiceTotalAmount');
				this.$refs.form.clearValidate('relBillId');
				this.rules.relBillId = []
			} else {
				this.model.invoiceTotalAmount = ''
				this.taxRateData = []; // 税率信息
				this.$refs.form.clearValidate('invoiceTotalAmount');
				this.rules.relBillId = [
					{ required: true, message: '请选择关联已开票申请单!', trigger: 'change'},
				]
				this.formData = []
			}
			// 业主单位
			this.$set(this.model,'buyerUnit',null)
			// 纳税人识别号 taxpayerIdNo
			this.$set(this.model,'taxpayerIdNo',null)
			// 单位地址
			this.$set(this.model,'companyAddress',null)
			// 开户行
			this.$set(this.model,'bankName',null)
			// 银行账号
			this.$set(this.model,'bankAccountNo',null)
		},
		handleBuyerUnit(projectContract){
			//根据合同带出业主单位
			erpOmcContractManagerEntrustFinalList({mainId:projectContract,isFk:"1"}).then(res=>{
				let resData=res.result;
				if(resData){
					let newArr=resData.map(item=>{return item.khdaId});
					let supplierData=newArr.join("&");
					this.buyerUnit="erp_purchase_supplier,enterprise_name,id,del_flag=0 and id in (" + supplierData + ")";
				}
			}).catch(e=>{
				console.error('异常')
			})
			// 选择发票信息后,携带出税率信息
			this.handleTaxRate(projectContract);
		},
		
		//选择业主单位
		selectBuyerUnit(data){
			// 查询业主单位
			querySupplierByIds({ids:data}).then(res=>{
				if(!!res&&!!res.result&&res.result.length!=0){
					// 调用原有带出数据方法
					this.selectBuyerUnitBack(res.result)
				}
			}).catch(e=>{
				console.error("请求异常---->", e)
			})
		},
		handleTaxRate(projectContract){
			let param={
				contractId:projectContract
			}
			if (this.model.id) {
				param.billId = this.model.id
			}
			if (this.model.relBillId) {
				param.billCancelId = this.model.relBillId
			}
			//根据合同带出税率
			queryContractRateFinal(param).then(res=>{
				this.taxRateData = res.result || []
			}).catch(e=>{
				console.error("请求异常---->", e)
			})
		},
		sellerUnitBack(val){
			let item = [val]
			//判断不为空
			if(!!this.model.sellerUnit && item.length > 0|| this.model.relBillId) {
				//判断销售方单位是否变化
				if(this.sellerUnitBackups !== item[0].id || this.relBillIdBackups !== this.model.relBillId) {
					if(this.formData.length > 0 || !!this.model.relBillId) {
						const that = this;
						uni.showModal({
						  title: '是否确认',
						  content: '是否确认切换销售方单位，此操作将会清空关联已开票申请单和开票信息明细中已填写的所有信息？',
						  success(res) {
						    if (res.confirm) {
						      //确认后进行改变
						      that.sellerUnitBackups = that.model.sellerUnit
						      that.relBillIdBackups = null
									that.formData = [] // 清空子表数据
									that.taxRateData = [];
						      // 清空关联已开票申请单
						      that.$set(that.model, 'relBillId', '')
						      //清空子表数据
						      that.dataSource = []
						      // 清空由表带出的数据
						      // 业主单位
						      that.$set(that.model,'buyerUnit','')
						      // 纳税人识别号 taxpayerIdNo
						      that.$set(that.model,'taxpayerIdNo','')
						      // 单位地址
						      that.$set(that.model,'companyAddress','')
						      // 开户行
						      that.$set(that.model,'bankName','')
						      // 银行账号
						      that.$set(that.model,'bankAccountNo','')
						      
						      // 总开票金额
									that.$set(that.model,'invoiceTotalAmount',0)
						      // if (that.model.isCrossMonthInvalid == '0'){
						      // 	that.$set(that.model,'invoiceTotalAmount',0)
						      // }
						      //获取财务开票人
						      queryEmpIdByCompanyIdAndPostCode({'companyId':that.model.sellerUnit,'postCode':'GSSW'}).then((res)=>{
						      	if(res.success){
						      		var data = ''
											if (res.result && res.result.length > 0) {
												let arr = res.result.split(',')
												data = arr[0]
											}
						      		that.$set(that.model,'invoiceApplicant',data);
						      	}
						      })
						    } else if (res.cancel) {
						      that.model.sellerUnit = that.sellerUnitBackups
						      that.model.relBillId = that.relBillIdBackups
						      //获取财务开票人
						      queryEmpIdByCompanyIdAndPostCode({'companyId':that.model.sellerUnit,'postCode':'GSSW'}).then((res)=>{
						      	if(res.success){
						      		var data = ''
						      		if (res.result && res.result.length > 0) {
						      			let arr = res.result.split(',')
						      			data = arr[0]
						      		}
						      		that.$set(that.model,'invoiceApplicant',data);
						      	}
						      })
						    }
						  },
						})
					} else {
						const that = this;
						this.sellerUnitBackups = item[0].id
						//获取财务开票人
						queryEmpIdByCompanyIdAndPostCode({'companyId':that.model.sellerUnit,'postCode':'GSSW'}).then((res)=>{
							if(res.success){
								var data = ''
								if (res.result && res.result.length > 0) {
									let arr = res.result.split(',')
									data = arr[0]
								}
								if (data) {
									var arr = data.split(',')
									that.$set(that.model,'invoiceApplicant',arr[0]);
								}
								
							}
						})
					}
				}
			}
			// 关联已开票申请单有值 则清空
			if(this.model.relBillId){
				this.$set(this.model, 'relBillId', '')
			}
		},
		addForm() {
		  if (this.validateCT()) {
		    this.index = null
				this.basicForm = {}
		    this.showFormModal = true
				this.$nextTick(() => {
					this.$refs.dataForm.loadList([])
					this.$refs.dataForm.isAdd = true
					this.$refs.dataForm.loadList(this.formData)
				})
		  }
		},
		handleFormSubmit([data, index]) {
		  this.showFormModal = false
		  if (typeof index === 'number') {
		    this.$set(this.formData, index, data)
		  } else {
		    this.formData.push(data)
		  }
		  if (this.formData && this.formData.length == 1) {
		  	this.initBuyerInfo()
		  }
			if (this.formData && this.formData.length) {
				this.getTotalMoney(this.formData)
			} else {
				this.model.invoiceTotalAmount = 0
			}
		},
		// 获取总金额数据
		getTotalMoney (data) {
			// if (this.model.isCrossMonthInvalid == 1) {
			// 	return false
			// }
			let count = 0
			data.forEach((item, index) => {
				count = count + Number(item.invoiceAmount)
			})
			this.model.invoiceTotalAmount = Number(count).toFixed(2)
		},
		
		handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
			this.initBuyerInfo()
			if (this.formData && this.formData.length) {
				this.getTotalMoney(this.formData)
			} else {
				this.model.invoiceTotalAmount = 0
			}
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
			if (!this.model.isCrossMonthInvalid) {
				uni.showToast({
				  title: '请选择是否作废!',
				  icon: 'none',
				})
				return false
			}
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
			this.$nextTick(() => {
				this.openFormModal()
				this.$refs.dataForm.loadList([this.basicForm])
				this.$refs.dataForm.isAdd = false
				this.$refs.dataForm.loadList(this.formData)
			})
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
			// 当formData里没有值的时候才会清除联动的数据
			// if (!this.formData  || this.formData.length == 0) {
			// 	this.initBuyerInfo()
			// }
			this.initBuyerInfo()
			if (this.formData && this.formData.length) {
				this.getTotalMoney(this.formData)
			} else {
				this.model.invoiceTotalAmount = 0
				this.taxRateData = [] // 置空税率信息
			}
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
			this.showFormModal = false
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = Object.assign({},this.basicForm)
    },
		
		handleEditFormRate([item, index]) {
			if (!this.model.isCrossMonthInvalid) {
				uni.showToast({
				  title: '请选择是否作废!',
				  icon: 'none',
				})
				return false
			}
		  this.basicFormRate = { ...item }
		  this.index = index
		  this.showFormModalRate = true
			this.$nextTick(() => {
				this.openFormModalRate()
			})
		},
		handleRemoveFormRate(item) {
		  this.taxRateData = this.taxRateData.filter((i) => i !== item)
		},
		closeFormModalRate() {
		  this.$refs.dataFormRate.reset()
		  this.basicFormRate = {}
		  this.index = null
			this.showFormModalRate = false
		},
		openFormModalRate() {
		  this.$refs.dataFormRate.basicForm = Object.assign({},this.basicFormRate)
		},
		handleCopyFormRate([item, index]) {
		  this.taxRateData.push({
		    ...item,
		  })
		  this.$refs.uToast.show({
		  	message:'复制成功!'
		  })
		},
		addFormRate() {
			if (!this.model.isCrossMonthInvalid) {
				uni.showToast({
				  title: '请选择是否作废!',
				  icon: 'none',
				})
				return false
			}
		  this.index = null
			this.basicFormRate = {}
		  this.showFormModalRate = true
		},
		/**
		 * 子表单新增点击确认
		 */
		handleFormSubmitRate([data, index]) {
		  this.showFormModalRate = false
		  if (typeof index === 'number') {
		    this.$set(this.taxRateData, index, data)
		  } else {
		    this.taxRateData.push(data)
		  }
		},
    // queryBillByProject(item) {
    //   this.$set(this.model, 'applicant', item.signUnit)
    //   this.$set(this.model, 'projectYear', item.year)
    //   this.$set(this.model, 'projectBusiTeamId', item.teamName)
    //   queryBillByProject({ projectId: this.model.projectId }).then((res) => {
    //     if (res.success) {
    //       let data = res.result
    //       if (data) {
    //         this.$set(this.model, 'projectPaidTotalAmount', data.projectTotalAmount)
    //         this.projectPaidTotalAmount = data.projectTotalAmount
    //         this.constructTotalAmount = data.constructAmount
    //       }
    //     }
    //   })
    // },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo()
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo.employee.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
			this.taxRateData = []
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
			this.model = Object.assign({},data)
			const res = await queryByIdInvoiceChildren({billId: this.id}) // 获取发票信息
			this.formData = res.result
			const dataRecordList = await erpFinanceInvoiceHandleRecordList({billId: this.id,pageNo: 1, pageSize: 100 })
			this.dataSource = dataRecordList.result.records || dataRecordList.result  || []
			// 获取税率信息
			const rateList = await erpFinanceInvoiceTaxRateRecordList({billId: this.id,pageNo: 1, pageSize: 100 })
			this.taxRateData = rateList.result.records ||rateList.result || []
			if(this.formData.length>0){
				//处理业主单位
				this.oldprojectContract = this.formData[0].projectContract
				this.handleBuyerUnit(this.formData[0].projectContract);
			}
			// 根据开票类型修改必填项
			this.changeInvoiceCategory()
			// this.radioChange(this.model.isCrossMonthInvalid)
			// 初始化销售方单位和团队back
			if(!!this.model.sellerUnit&&!!this.model.teamId){
				this.sellerUnitBackups = this.model.sellerUnit
				this.teamIdBackups = this.model.teamId
			}
			if(this.model.relBillId){
				this.relBillIdBackups = this.model.relBillId
			}
    },
    validateForm() {
      // return this.$refs.form.validate().then(async () => {
      //   if (this.dataSource.length === 0) {
      //     this.$u.toast('请添加开票明细')
      //     return Promise.reject('请添加开票明细')
      //   }
      //   const response = await addInvoiceHandleRecordList(this.model.billNo, this.formData)
      //   if (response.success) {
      //     return Promise.resolve(response)
      //   } else {
      //     this.$u.toast(response.message)
      //     return Promise.reject(response.message)
      //   }
      // })
			if(this.judgeInvoiceHandleList()){
				this.$u.toast('同一个款项不能重复开票!')
				return Promise.reject('同一个款项不能重复开票!')
			}
			if(this.judgeTaxRateHandle()){
				this.$u.toast('税率信息的本次开票金额总和必须等于总开票金额!')
				return Promise.reject('税率信息的本次开票金额总和必须等于总开票金额!')
			}
			return this.$refs.form.validate()
    },
		judgeInvoiceHandleList() {
			const groupedData = this.formData.reduce((acc, item) => {
				if (!acc[item.contractFund]) {
					acc[item.contractFund] = [];
				}
				acc[item.contractFund].push(item);
				return acc;
			}, {});
			for (const key in groupedData) {
				if(groupedData[key].length>1){
					return true;
				}
			}
			return false;
		},
		judgeTaxRateHandle() {
			let count = 0
			console.log(this.taxRateData);
			this.taxRateData.forEach((item, index) => {
				count = count + Number(item.invoiceAmount || 0)
			})
			if(this.model.invoiceTotalAmount!=count){
				return true;
			}
			return false;
		},
    validateCT() {
      if (!this.model.sellerUnit) {
        uni.showToast({
          title: '请选择销售方单位!',
          icon: 'none',
        })
        return false
      }
      if (!this.model.teamId) {
        uni.showToast({
          title: '请选择经营团队!',
          icon: 'none',
        })
        return false
      }
			if (!this.model.isCrossMonthInvalid) {
				uni.showToast({
				  title: '请选择是否作废!',
				  icon: 'none',
				})
				return false
			}
      return true
    },
    /**
     * 业主单位由子表第一条数据带出
     */
    initBuyerInfo() {
      const row = this.formData[0]
      if (!!row && !!row.projectContract){
				// if (!!row && !!row.projectId){
				// erpOmcProjectId({ id: row.projectId }).then((res) => {
				//   if (res && res.result && res.result.ownerUnit && this.model.buyerUnit != res.result.ownerUnit ) {
				// 		this.$set(this.model, 'buyerUnit', res.result.ownerUnit)
				//     // 查询业主单位
				//     querySupplierByIds({ ids: res.result.ownerUnit })
				//       .then((res) => {
				//         if (res && res.result && res.result.length != 0 ) {
				//           // 调用原有带出数据方法
				//           this.selectBuyerUnitBack(res.result)
				//         }
				//       })
				//   }
				// })
				this.handleBuyerUnit(row.projectContract);
				if(this.oldprojectContract != row.projectContract){
					// 清空带出的相应字段
					// 业主单位
					this.$set(this.model,'buyerUnit','')
					// 纳税人识别号 taxpayerIdNo
					this.$set(this.model,'taxpayerIdNo','')
					// 单位地址
					this.$set(this.model,'companyAddress','')
					// 开户行
					this.$set(this.model,'bankName','')
					// 银行账号
					this.$set(this.model,'bankAccountNo','')
				} else {
					this.oldprojectContract = row.projectContract
				}
			} else{
				// 清空带出的相应字段
				// 业主单位
				this.$set(this.model,'buyerUnit','')
				// 纳税人识别号 taxpayerIdNo
				this.$set(this.model,'taxpayerIdNo','')
				// 单位地址
				this.$set(this.model,'companyAddress','')
				// 开户行
				this.$set(this.model,'bankName','')
				// 银行账号
				this.$set(this.model,'bankAccountNo','')
			}
    },
    selectBuyerUnitBack(item) {
      const dateOne = item[0]
      // 纳税人识别号
      // this.rules.taxpayerIdNo = []
      this.$set(this.model, 'taxpayerIdNo', dateOne.enterpriseCreditCode || '')
      // 单位地址
      // this.rules.companyAddress = []
      this.$set(this.model, 'companyAddress', dateOne.enterpriseAddress || '')
      // 开户行
      // this.rules.bankName = []
      this.$set(this.model, 'bankName', dateOne.bankName || '')
      // 银行账号
      // this.rules.bankAccountNo = []
      this.$set(this.model, 'bankAccountNo', dateOne.bankAccountNo || '')
    },
		async initDicts(){
			initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
				if (res.success) {
					this.$set(this.dictOptions, 'teamManager', res.result)
				}
			})
			initDictOptions('erp_company_files,file_name,id').then((res) => {
				if (res.success) {
					this.$set(this.dictOptions, 'companyFiles', res.result)
				}
			})
		},
		getCreateTime() {
			let createTime = this.model.createTime;
			let date = createTime.substring(0,10)
			return date.substring(0,4) +'年'+ date.substring(5,7)+'月' + date.substring(8,10)+'日';
		},
    async onSubmit() {
      await this.validateForm()
			this.isSubmit = true
			try {
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
				let teamName = this.model.teamId ? (filterMultiDictText(this.dictOptions['teamManager'], this.model.teamId + '')) : ''
				let companyName = filterMultiDictText(this.dictOptions['companyFiles'], this.model.sellerUnit + '')
				let createTime = this.getCreateTime()
				let amount = 0
				if(!!this.formData&&this.formData.length>0){
					for (let i = 0; i < this.formData.length; i++) {
						amount += Number(this.formData[i].invoiceAmount)
					}
				}
				// 迭代16.7 取销售方单位-经营团队-申请人-申请日期（年月日）-金额（取子表中开票金额之和）
				this.model.bpmBizTitle =  (this.model.sellerUnit ? companyName + ' - ' : '') + (this.model.teamId ? teamName + ' - ' : '') + this.userInfo?.employee?.name + ' - ' + createTime + (amount ? ' - ' + amount : '')// 标题
			  const response = await url({
			    ...this.model,
			    invoiceExpensesDetails: this.formData,
					invoiceTaxRateDetails: this.taxRateData
			  })
			  if (response.success) {
					var that = this
					
					// 获取流程列表
					if (this.model.id) {
						this.getProcessList(this.model.id)
					} else {
					// 判断添加的时候是否有返回id值
						if (response.result) {
							this.getProcessList(response.result)
						}
			
					}
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							// that.isSubmit = false
						}
					})
			  }
			} finally {
			  // error
			}
    },
    async onDraft() {
      // await this.validateForm()
			this.isSubmit = true
			try {
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
				let teamName = this.model.teamId ? (filterMultiDictText(this.dictOptions['teamManager'], this.model.teamId + '')) : ''
				let createTime = this.getCreateTime()
				let amount = 0
				if(this.formData&&this.formData.length){
					for (let i = 0; i < this.formData.length; i++) {
						amount += Number(this.formData[i].invoiceAmount)
					}
				}
				//迭代16.7 取经营团队-申请人-申请日期（年月日）-金额（取子表中开票金额之和）
				this.model.bpmBizTitle = (teamName ? teamName + ' - ' : '') + this.userInfo?.employee?.name + ' - ' + createTime + (amount? ' - ' + amount :'') //标题
			  const response = await url({
			    ...this.model,
			    invoiceExpensesDetails: this.formData,
					invoiceTaxRateDetails: this.taxRateData
			  })
			  if (response.success) {
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							this.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
			  }
			} finally {
				// error
			}
    },
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		}
  },
  watch: {
    'model.applicant'(current, old) {
      if (old && current && old !== current) {
        this.backUpApplicant = old
      }
    },
    'model.projectBusiTeamId'(current, old) {
      if (old && current && old !== current) {
        this.backUpTeamId = old
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
	::v-deep {
		.u-form-item__body {
			padding-top: 2px;
			padding-bottom: 2px;
		}
	}
}

.checkbox-item {
	display: flex;
	align-items: center;
}
</style>
